package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


/**
 * 定义服务消费端Controller,在这个Controller对象的方法
 * 中实现对远端服务sca-provider的调用
 */
@RestController
public class ConsumerController {

    /**
     * 从spring容器获取一个RestTemplate对象，
     * 基于此对象实现远端服务调用
     */
    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.application.name}")
    private String appName;
    /**
     * 在此方法中通过一个对象调用远端sca-provider中的服务
     * @return
     */
    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho01() {
        // 1.定义要调用的远端服务的url
        String url = "http://localhost:8081/provider/echo/"+appName;
        // 2.基于restTemplate对象中的相关方法进行服务调用
        return restTemplate.getForObject(url,String.class);
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho02() {
        // 1.定义要调用远端服务的url
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
        return restTemplate.getForObject(url,String.class);
    }

    @Autowired
    private RestTemplate loadBalancedRestTemplate;

    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho03() {
        String url = "http://sca-provider/provider/echo/"+appName;
        return loadBalancedRestTemplate.getForObject(url,String.class);
    }
}
